import {
  budgetPageApi,
  addBudgetApi,
  editBudgetApi,
  delBudgetApi
} from '@/api/workflow/budget'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { BudgetModel } from '@/api/model/budget-model'
import { userInfo } from '~/types/user'
import { userInfoModel } from '@/api/model/userModel'
import dayjs from 'dayjs'

type Props = {
  handleType: Ref<'add' | 'edit' | 'check'>
  handleTag: Ref<string>
  budgetModalShow: Ref<boolean>
  budgetForm: Ref<Partial<BudgetModel>>
  proTableInst: Ref<ProTableInst | null>
  userInfo: Ref<userInfo<userInfoModel>>
}

export const useBudgetApi = ({
  handleType,
  handleTag,
  budgetModalShow,
  budgetForm,
  proTableInst,
  userInfo
}: Props) => {
  const confirmLoading = ref(false)

  // 获取预算列表
  const fetchBudgetPage = async (
    pageRequest: PageRequest,
    queryParams: BudgetModel
  ) => {
    const res = await budgetPageApi({
      ...queryParams,
      orgId: userInfo.value.orgId,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  // 新增or修改预算
  const fetchAddOrEditBudget = async () => {
    try {
      confirmLoading.value = true
      const fetch = handleType.value === 'add' ? addBudgetApi : editBudgetApi
      const data =
        handleType.value === 'add'
          ? {
              ...budgetForm.value,
              receivePerson: userInfo.value.userName,
              receivePersonId: userInfo.value.userId,
              receiveBranch: userInfo.value.orgName,
              receiveBranchId: userInfo.value.orgId,
              receiveDate: dayjs().format('YYYY-MM-DD')
            }
          : {
              ...budgetForm.value
            }
      if (data.__displayValue__) delete data.__displayValue__
      const res = await fetch(data)
      if (res.code === '0000') {
        useMsg('success', handleTag.value + '成功')
        proTableInst.value?.reload()
        budgetModalShow.value = false
      }
    } catch (e) {
      console.log(e)
    } finally {
      confirmLoading.value = false
    }
  }

  // 删除预算
  const fetchDelBudget = async (id) => {
    try {
      const res = await delBudgetApi({ id })
      if (res.code === '0000') {
        useMsg('success', '删除成功')
        proTableInst.value?.reload()
      }
    } catch (e) {
      console.log(e)
    }
  }

  return {
    fetchBudgetPage,
    fetchAddOrEditBudget,
    fetchDelBudget,
    confirmLoading
  }
}
